package com.edu.scau.dao.implement;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.*;
import com.edu.scau.dao.ShoppingCartDao;
import com.edu.scau.entity.Commodity;
import com.edu.scau.entity.OrderForm;
import com.edu.scau.entity.ShoppingCart;
import com.edu.scau.entity.User;

@Component
public class ShoppingCartDaoImpl implements ShoppingCartDao{
	@Resource(name = "sessionFactory")
	private SessionFactory  factory; 

	public SessionFactory getFactory() {
		return factory;
	}

	public void setFactory(SessionFactory factory) {
		this.factory = factory;
	}
	public boolean update(ShoppingCart cart){
		try {
			// TODO Auto-generated method stub
			Session session=factory.getCurrentSession();
			
			session.update(cart);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
		
	}
	
	
	public boolean save(ShoppingCart cart){
		try {
			Session session=factory.getCurrentSession();
			session.save(cart);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public boolean delete(ShoppingCart cart){
		try {
			// TODO Auto-generated method stub
			Session session=factory.getCurrentSession();
			session.delete(cart);
		} catch (HibernateException e) {
			// TODO Auto-generated catch bloc
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public List<ShoppingCart> queryByUserId(int userId){
		Session session=factory.getCurrentSession();
		List<User> form=new ArrayList<User>();
		Criteria criteria=session.createCriteria(User.class);
		form=(ArrayList<User>) criteria.add(Restrictions.like("id", userId)).list();
		if(form.isEmpty())
		return null;
		return  queryByUser(form.get(0));
		
	}
	
	public List<ShoppingCart> queryByUser(User user) {
		Session session=factory.getCurrentSession();
		List<ShoppingCart> form=new ArrayList<ShoppingCart>();
		Criteria criteria=session.createCriteria(ShoppingCart.class);
		form=(ArrayList<ShoppingCart>) criteria.add(Restrictions.like("user", user)).list();
		return form;
	}

	
	
	
}
